<template>
  <div class="leaderboard">
    <div class="page-header">
      <h1>排行榜</h1>
      <div class="leaderboard-tabs">
        <button 
          @click="activeTab = 'level'" 
          :class="['tab-btn', { active: activeTab === 'level' }]"
        >
          等级榜
        </button>
        <button 
          @click="activeTab = 'experience'" 
          :class="['tab-btn', { active: activeTab === 'experience' }]"
        >
          经验榜
        </button>
        <button 
          @click="activeTab = 'accuracy'" 
          :class="['tab-btn', { active: activeTab === 'accuracy' }]"
        >
          准确率榜
        </button>
        <button 
          @click="activeTab = 'cases'" 
          :class="['tab-btn', { active: activeTab === 'cases' }]"
        >
          破案榜
        </button>
      </div>
    </div>
    
    <div class="leaderboard-content">
      <div class="leaderboard-list">
        <div 
          v-for="(player, index) in sortedPlayers" 
          :key="player.id"
          :class="['leaderboard-item', { 'current-user': player.id === currentPlayerId }]"
        >
          <div class="rank">
            <div :class="['rank-badge', getRankClass(index)]">
              {{ index + 1 }}
            </div>
          </div>
          
          <div class="player-info">
            <div class="avatar">
              <img 
                v-if="player.avatar" 
                :src="player.avatar" 
                :alt="player.nickname"
                @error="handleAvatarError($event, player.id)"
              />
              <div v-else class="avatar-placeholder">
                {{ player.nickname.charAt(0).toUpperCase() }}
              </div>
            </div>
            
            <div class="player-details">
              <h3>{{ player.nickname }}</h3>
              <p class="username">@{{ player.username }}</p>
              <p class="player-level">等级 {{ player.level }}</p>
            </div>
          </div>
          
          <div class="player-stats">
            <div class="stat-item">
              <span class="stat-label">{{ getStatLabel() }}</span>
              <span class="stat-value">{{ getStatValue(player) }}</span>
            </div>
          </div>
          
          <div class="player-actions">
            <button 
              v-if="player.id !== currentPlayerId && playerStore.isLoggedIn"
              @click="handleAddFriend(player.id)"
              class="add-friend-btn"
            >
              添加好友
            </button>
            <button 
              @click="handleViewProfile(player.id)"
              class="view-profile-btn"
            >
              查看档案
            </button>
          </div>
        </div>
      </div>
      
      <div class="leaderboard-summary">
        <h3>统计信息</h3>
        <div class="summary-stats">
          <div class="summary-item">
            <div class="summary-value">{{ totalPlayers }}</div>
            <div class="summary-label">总玩家数</div>
          </div>
          <div class="summary-item">
            <div class="summary-value">{{ onlinePlayersCount }}</div>
            <div class="summary-label">在线玩家</div>
          </div>
          <div class="summary-item">
            <div class="summary-value">{{ averageLevel }}</div>
            <div class="summary-label">平均等级</div>
          </div>
          <div class="summary-item">
            <div class="summary-value">{{ totalCasesSolved }}</div>
            <div class="summary-label">总破案数</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { usePlayerStore } from '@/stores/player';
import type { Player } from '@/entities/Player';

const router = useRouter();
const playerStore = usePlayerStore();

// 状态
const activeTab = ref<'level' | 'experience' | 'accuracy' | 'cases'>('level');

// 计算属性
const currentPlayerId = computed(() => {
  return playerStore.currentPlayer?.id;
});

const sortedPlayers = computed(() => {
  const players = [...playerStore.players];
  
  switch (activeTab.value) {
    case 'level':
      return players.sort((a, b) => b.level - a.level);
    case 'experience':
      return players.sort((a, b) => b.stats.experience - a.stats.experience);
    case 'accuracy':
      return players.sort((a, b) => b.stats.accuracy - a.stats.accuracy);
    case 'cases':
      return players.sort((a, b) => b.stats.casesSolved - a.stats.casesSolved);
    default:
      return players;
  }
});

const totalPlayers = computed(() => {
  return playerStore.players.length;
});

const onlinePlayersCount = computed(() => {
  return playerStore.onlinePlayers.length;
});

const averageLevel = computed(() => {
  if (playerStore.players.length === 0) return 0;
  const totalLevel = playerStore.players.reduce((sum, player) => sum + player.level, 0);
  return Math.round(totalLevel / playerStore.players.length);
});

const totalCasesSolved = computed(() => {
  return playerStore.players.reduce((sum, player) => sum + player.stats.casesSolved, 0);
});

// 方法
const getRankClass = (index: number) => {
  if (index === 0) return 'rank-gold';
  if (index === 1) return 'rank-silver';
  if (index === 2) return 'rank-bronze';
  return 'rank-normal';
};

const getStatLabel = () => {
  switch (activeTab.value) {
    case 'level':
      return '等级';
    case 'experience':
      return '经验值';
    case 'accuracy':
      return '准确率';
    case 'cases':
      return '破案数';
    default:
      return '统计';
  }
};

const getStatValue = (player: Player) => {
  switch (activeTab.value) {
    case 'level':
      return player.level;
    case 'experience':
      return player.stats.experience;
    case 'accuracy':
      return `${player.stats.accuracy.toFixed(1)}%`;
    case 'cases':
      return player.stats.casesSolved;
    default:
      return '';
  }
};

const handleAvatarError = (event: Event, playerId: string) => {
  const img = event.target as HTMLImageElement;
  img.style.display = 'none';
  img.nextElementSibling?.classList.add('show');
};

const handleAddFriend = async (playerId: string) => {
  try {
    await playerStore.addFriend(playerId);
    alert('好友添加成功！');
  } catch (error) {
    alert('添加好友失败：' + (error as Error).message);
  }
};

const handleViewProfile = (playerId: string) => {
  router.push(`/player/${playerId}`);
};

onMounted(async () => {
  // 确保玩家数据已加载
  if (playerStore.players.length === 0) {
    try {
      await playerStore.loadPlayers();
    } catch (error) {
      console.error('加载玩家数据失败:', error);
    }
  }
});
</script>

<style scoped>
.leaderboard {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
  padding: 24px 0;
  border-bottom: 1px solid var(--color-border);
}

.page-header h1 {
  font-size: 32px;
  font-weight: 700;
  color: var(--color-text);
  margin: 0;
}

.leaderboard-tabs {
  display: flex;
  gap: 8px;
  background: var(--color-background-soft);
  padding: 4px;
  border-radius: 8px;
}

.tab-btn {
  padding: 8px 16px;
  background: transparent;
  color: var(--color-text-secondary);
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s ease;
}

.tab-btn.active {
  background: white;
  color: var(--color-primary);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.tab-btn:hover:not(.active) {
  color: var(--color-text);
}

.leaderboard-content {
  display: grid;
  grid-template-columns: 1fr 300px;
  gap: 32px;
}

.leaderboard-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.leaderboard-item {
  display: grid;
  grid-template-columns: 60px 1fr 120px 120px;
  gap: 16px;
  align-items: center;
  padding: 16px;
  background: var(--color-background);
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.2s ease;
}

.leaderboard-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.leaderboard-item.current-user {
  background: linear-gradient(135deg, var(--color-primary) 0%, var(--color-primary-dark) 100%);
  color: white;
}

.rank {
  display: flex;
  justify-content: center;
}

.rank-badge {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  font-size: 16px;
}

.rank-gold {
  background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
  color: #b8860b;
}

.rank-silver {
  background: linear-gradient(135deg, #c0c0c0 0%, #e8e8e8 100%);
  color: #808080;
}

.rank-bronze {
  background: linear-gradient(135deg, #cd7f32 0%, #e4a852 100%);
  color: #8b4513;
}

.rank-normal {
  background: var(--color-background-soft);
  color: var(--color-text);
}

.player-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  overflow: hidden;
  background: var(--color-background-soft);
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  font-weight: 700;
  color: var(--color-primary);
}

.avatar-placeholder.show {
  display: flex;
}

.player-details h3 {
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 2px 0;
}

.username {
  font-size: 14px;
  opacity: 0.8;
  margin: 0 0 2px 0;
}

.player-level {
  font-size: 12px;
  opacity: 0.7;
  margin: 0;
}

.leaderboard-item.current-user .username,
.leaderboard-item.current-user .player-level {
  color: rgba(255, 255, 255, 0.9);
}

.player-stats {
  text-align: center;
}

.stat-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.stat-label {
  font-size: 12px;
  opacity: 0.7;
}

.stat-value {
  font-size: 16px;
  font-weight: 600;
}

.player-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.add-friend-btn,
.view-profile-btn {
  padding: 8px 12px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 12px;
  font-weight: 500;
  transition: all 0.2s ease;
}

.add-friend-btn {
  background: var(--color-primary);
  color: white;
}

.add-friend-btn:hover {
  background: var(--color-primary-dark);
}

.view-profile-btn {
  background: transparent;
  color: var(--color-primary);
  border: 1px solid var(--color-primary);
}

.view-profile-btn:hover {
  background: var(--color-primary);
  color: white;
}

.leaderboard-item.current-user .add-friend-btn {
  background: white;
  color: var(--color-primary);
}

.leaderboard-item.current-user .view-profile-btn {
  background: transparent;
  color: white;
  border-color: white;
}

.leaderboard-item.current-user .view-profile-btn:hover {
  background: white;
  color: var(--color-primary);
}

.leaderboard-summary {
  background: var(--color-background);
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  height: fit-content;
}

.leaderboard-summary h3 {
  font-size: 20px;
  font-weight: 700;
  margin: 0 0 24px 0;
  color: var(--color-text);
}

.summary-stats {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid var(--color-border);
}

.summary-item:last-child {
  border-bottom: none;
}

.summary-value {
  font-size: 18px;
  font-weight: 600;
  color: var(--color-primary);
}

.summary-label {
  font-size: 14px;
  color: var(--color-text-secondary);
}

@media (max-width: 1024px) {
  .leaderboard-content {
    grid-template-columns: 1fr;
  }
  
  .leaderboard-summary {
    order: -1;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .leaderboard-tabs {
    width: 100%;
    justify-content: center;
  }
  
  .leaderboard-item {
    grid-template-columns: 60px 1fr;
    gap: 12px;
  }
  
  .player-stats,
  .player-actions {
    grid-column: 2;
  }
  
  .player-actions {
    flex-direction: row;
  }
}
</style>